package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.RegexUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.AccountRegisterController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.AccountDao;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.AccountRegisterModel;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.net.listener.HttpRequestErrListener;
import com.shuqi.model.parse.parser.AccountRegisterParser.AccountRegisterParserInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 邮箱注册界面
 * 
 * @author liyizhe
 */

public class MailRegisterActivity extends ActivityBase implements OnClickListener,
        OnFocusChangeListener, IEventListener, HttpRequestErrListener {

    /**
     * 密码是否可见图标
     */
    private int iVisible;

    private TextView mTextShuQi = null;// 书旗用户协议
    private ImageView mImgVisible = null;// 可见图标
    private EditText mEditEmail;// 邮箱
    private EditText mEditPwd;// 密码
    private TextView mTextOk = null;// 确定
    private CheckBox mCheckBox = null;

    private TextView mTextMailPoinTextView = null; // 邮箱提示
    private TextView mTextPwdPoinTextView = null; // 密码提示

    private ToastDialog mLoadingDialog;// 底部loading

    private String mCurrentMail;// 记录当前用户email
    private String mCurrentPwd;// 记录当前用户密码

    private final int INIT = EventTypeConstants.BASE;
    private final int SAVEDETAILS = INIT + 1;
    private final int INITSUCCESS = SAVEDETAILS + 1;
    private final int NETERROR = INITSUCCESS + 1;

    List<BasicNameValuePair> params;// 传的参数
    AccountRegisterParserInfo info = null;// 返回的信息

    AccountRegisterController controller;
    private CommonTitle mTitle;

    private ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case INITSUCCESS:
                    activityInitData();
                    break;
                case NETERROR:
                    hideLoadingDialog();
                    showMsg("网络连接超时");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.controller =
                (AccountRegisterController) MainController.getMainManagerInstance()
                        .createController(MainController.CONTROLLER_ID_MAIL_MOBILE_REGISTER, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_mail_register);
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                // 读取数据 写处理逻辑
                info = (AccountRegisterParserInfo) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            case EventTypeConstants.EVENT_EXC_IO_2:
                handler.sendEmptyMessage(NETERROR);
                break;
            default:
                handler.sendEmptyMessage(NETERROR);
                break;
        }
    }

    @Override
    public void activityLogicForward() {
        iVisible = 0;

        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mTextShuQi = (TextView) findViewById(R.id.proxy_text2);
        mCheckBox = (CheckBox) findViewById(R.id.checkBox_mail);
        mEditEmail = (EditText) findViewById(R.id.edit_email);
        mEditPwd = (EditText) findViewById(R.id.edit_password);
        mImgVisible = (ImageView) findViewById(R.id.img_visible);
        mTextOk = (TextView) findViewById(R.id.mail_register_ok);
        mTextMailPoinTextView = (TextView) findViewById(R.id.mail_point);
        mTextPwdPoinTextView = (TextView) findViewById(R.id.pwd_point);

        mImgVisible.setOnClickListener(this);
        mTextOk.setOnClickListener(this);
        mTextShuQi.setOnClickListener(this);
        mEditEmail.setOnFocusChangeListener(this);
        mEditPwd.setOnFocusChangeListener(this);
        
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    @Override
    public void activityInitData() {
        if (info != null) {
            String msg = info.message;
            if (info.resultCode.equals("200")) {
                updateUserInfoToDB(info);
                AccountActivity.callRefreshAccountOnResume();
                showLoadingDialog(false, true, "注册成功");
            } else {
                showLoadingDialog(false, false, msg);
            }
        }
    }

    /**
     * 点击注册
     */
    private void startRegister() {
        if (!mCheckBox.isChecked()) {
            return;
        }
        String strEmail = mEditEmail.getText().toString().trim();
        String strPwd = mEditPwd.getText().toString().trim();
        mCurrentMail = strEmail;
        mCurrentPwd = strPwd;
        if(checkEmailInput(strEmail) && checkPasswordInput(strPwd)){
            showLoadingDialog(true, false, "正在注册");
            params = setParams();
            controller.handle(0, params);
        }
    }
    /** 检查密码输入 */
    private boolean checkPasswordInput(String strPwd){
        boolean isCheckPassed = false;
        if(TextUtils.isEmpty(strPwd)){
            isCheckPassed = false;
            showTips(mTextPwdPoinTextView, "请设置登录密码", true);
        }else if(strPwd.length() < 6){
            isCheckPassed = false;
            showTips(mTextPwdPoinTextView, "密码过短，请输入6-16位新密码", true);
        }else if(strPwd.length() > 16){
            isCheckPassed = false;
            showTips(mTextPwdPoinTextView, "密码过长，请输入6-16位新密码", true);
        }else{
            isCheckPassed = true;
            showTips(mTextPwdPoinTextView, "请设置登录密码", true);
        }
        return isCheckPassed;
    }
    /** 检查邮箱输入 */
    private boolean checkEmailInput(String strEmail){
        boolean isCheckPassed = false;
        if(TextUtils.isEmpty(strEmail)){
            isCheckPassed = false;
            showTips(mTextMailPoinTextView, "请输入邮箱账号", true);
        }else if(!RegexUtil.isEmail(strEmail)){
            isCheckPassed = false;
            showTips(mTextMailPoinTextView, "邮箱格式错误，请重新输入", true);
        }else{
            isCheckPassed = true;
            mTextMailPoinTextView.setVisibility(View.INVISIBLE);
        }
        return isCheckPassed;
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view.getId() == R.id.edit_email && hasFocus) {
            ((RelativeLayout) findViewById(R.id.layout_email)).setBackgroundResource(R.drawable.input_box_f);
            ((RelativeLayout) findViewById(R.id.layout_psw)).setBackgroundResource(R.drawable.input_box_n);
            showTips(mTextMailPoinTextView, "请输入真实有效邮箱，可用于密码找回", false);
        }else if(view.getId() == R.id.edit_password && hasFocus){
            ((RelativeLayout) findViewById(R.id.layout_email)).setBackgroundResource(R.drawable.input_box_n);
            ((RelativeLayout) findViewById(R.id.layout_psw)).setBackgroundResource(R.drawable.input_box_f);
            showTips(mTextPwdPoinTextView, "可输入6-16位字母或数字", false);
            checkEmailInput(mEditEmail.getText().toString());
        }
    }

    /** 账号密码提示 */
    private void showTips(TextView textView, String tips, boolean isError) {
        if (textView != null && !TextUtils.isEmpty(tips)) {
            textView.setVisibility(View.VISIBLE);
            textView.setTextColor(getResources().getColor(isError?R.color.hint_error_color:R.color.hint_color));
            textView.setText(tips);
        }
    }
    

    /**
     * @Des 描述 获取接口组织参数
     * @return List<BasicNameValuePair>
     */
    public List<BasicNameValuePair> setParams() {
        List<BasicNameValuePair> pwParams = new ArrayList<BasicNameValuePair>();
        String strEmail = mEditEmail.getText().toString();
        String strPwd = mEditPwd.getText().toString();

        String key = "c56cf32e9a52a265ae47cd50570266cc";
        long timestamp = System.currentTimeMillis();
        String strTimestamp = timestamp + "";
        String md5_key_sb = key + timestamp;
        String md5_key = Util.MD5(md5_key_sb.toString());
        pwParams.add(new BasicNameValuePair("key", md5_key));// md5
        pwParams.add(new BasicNameValuePair("timestamp", strTimestamp));// 时间戳

        pwParams.add(new BasicNameValuePair("type", AccountRegisterModel.TYPE_REGISTER_EMAIL));
        pwParams.add(new BasicNameValuePair("account", strEmail));
        if (!TextUtils.isEmpty(strPwd)) {
            pwParams.add(new BasicNameValuePair("password", strPwd));
        }

        return pwParams;
    }

    /**
     * 获得返回数据后保存
     * 
     * @param info
     */
    private void updateUserInfoToDB(AccountRegisterParserInfo info) {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(mCurrentMail)) {
            user.setEmail(mCurrentMail);
        }
        if (!TextUtils.isEmpty(mCurrentPwd)) {
            user.setPassword(mCurrentPwd);
        }
        if (!TextUtils.isEmpty(info.uid)) {
            user.setUserId(info.uid);
        }
        if (!TextUtils.isEmpty(info.nickName)) {
            user.setNickName(info.nickName);
        }
        if (!TextUtils.isEmpty(info.session)) {
            user.setSession(info.session);
        }
        if (!TextUtils.isEmpty(info.gender)) {
            user.setGender(info.gender);
        }
        AccountDao.getInstance().saveUserInfo(user);
//        UserInfoHelper.insertOrUpdateUserInfo(getApplicationContext(), user);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.img_visible: {
                if (iVisible == 1) {
                    iVisible = 0;
                    mImgVisible.setImageResource(R.drawable.password_invisible);
                    mEditPwd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    iVisible = 1;
                    mImgVisible.setImageResource(R.drawable.password_visible);
                    mEditPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                break;
            }
            case R.id.mail_register_ok: {
                StatisticsUtils.onEvent(MailRegisterActivity.this,
                        StatisticsEventID.ACCOUNT_MAIL_RIGISTER_OVER);
                startRegister();
            }
                break;
            case R.id.proxy_text2: {
                WebKitActivity.openRegisterProtocol(this);
            }
                break;
            default:
                break;
        }
    }

    /**
     * 显示底部加载
     */
    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }




    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
